import { css } from '@emotion/react'
import { Popconfirm, Form, message, Input, Button, Table, type TableColumnType } from 'antd'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import type { WordsGroup } from '@/services/resources/words-library'

export function ManageGroups(props: { isGlobal: boolean; open: boolean; onFinish: () => void }) {
  const { isGlobal, open, onFinish } = props
  const type = isGlobal ? '全员' : '我的'
  return <EditModal title={`管理${type}话术库分组`} open={open} onCancel={onFinish} width={700}>
    {open ? <Content isGlobal={isGlobal} /> : null}
  </EditModal>
}

function Content({ isGlobal }: { isGlobal: boolean }) {
  const [groups, setGroups] = useState<WordsGroup[]>([])
  const load = useCallback(() => {
    void services.resources.wordsLibrary.loadGroups().then(groups => {
      setGroups(groups.filter(v => v.isGlobal === isGlobal))
    })
  }, [isGlobal])
  useEffect(() => load(), [load])

  const [editing, setEditing] = useState<WordsGroup | true | null>(null)
  function finishAdd() {
    load()
    setEditing(null)
  }

  async function remove(id: number) {
    const res = await services.resources.wordsLibrary.removeGroup(id)
    if (!res.success) void message.error(`话术分组删除失败：${res.error}`)
    load()
  }

  const columns: TableColumnType<WordsGroup>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      width: 200,
      render(_: unknown, group: WordsGroup) {
        return <div css={styles.actions}>
          <Button type="link" onClick={() => setEditing(group)}>
            重命名
          </Button>
          <Popconfirm
            title="确定删除分组吗？分组下的话术将变为“未分组”"
            onConfirm={() => void remove(group.id)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </div>
      },
    },
  ]

  return <div css={styles.wrap}>
    <header>
      <Button type="primary" onClick={() => setEditing(true)}>
        新建分组
      </Button>
    </header>
    <Table columns={columns} dataSource={groups} rowKey="id" />
    <EditGroupModal isGlobal={isGlobal} editing={editing} onFinish={finishAdd} />
  </div>
}

// ======================================

function EditGroupModal(props: {
  isGlobal: boolean
  editing: WordsGroup | true | null
  onFinish: (name?: string) => void
}) {
  const { isGlobal, editing, onFinish } = props
  const action = editing === true ? '新建' : '编辑'
  const title = `${action}${isGlobal ? '全员' : ''}话术分组`
  return <EditModal open={editing !== null} title={title} onCancel={() => onFinish()}>
    {editing !== null ? (
      <EditContent isGlobal={isGlobal} group={editing} onFinish={onFinish} />
    ) : null}
  </EditModal>
}

function EditContent(props: {
  isGlobal: boolean
  group: WordsGroup | true
  onFinish: (name?: string) => void
}) {
  const { isGlobal, group, onFinish } = props

  const [submitting, setSubmitting] = useState(false)

  const submit = useCallback(
    async (values: { name: string }) => {
      const name = values.name.trim()

      setSubmitting(true)
      const res = await (group === true
        ? services.resources.wordsLibrary.addGroup({ isGlobal, name })
        : services.resources.wordsLibrary.renameGroup({ isGlobal, id: group.id, name }))
      setSubmitting(false)

      if (res.success) onFinish(name)
      else void message.error(`话术分组保存失败：${res.error}`)
    },
    [isGlobal, group, onFinish],
  )

  return <main>
    <Form initialValues={{ name: group === true ? '' : group.name }} onFinish={submit}>
      <Form.Item name="name" rules={[{ required: true, message: '请输入分组名称' }]}>
        <Input placeholder="分组名称" />
      </Form.Item>
      <Form.Item noStyle>
        <div>
          <Button loading={submitting} type="primary" htmlType="submit">
            保存
          </Button>
        </div>
      </Form.Item>
    </Form>
  </main>
}

// ======================================

const styles = {
  wrap: css`
    padding: 20px;
    & > header {
      margin-bottom: 12px;
    }
  `,
  actions: css`
    button {
      padding-left: 0;
      padding-right: 0;
      margin-right: 1em;
    }
  `,
}
